//
//  ViewController.m
//  NSOperation
//
//  Created by niit on 16/3/24.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "ViewController.h"

#import "MyOperation.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    // 1. 创建一个队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    //
    queue.maxConcurrentOperationCount = 1;// 相当于串行
    
    // 2. 创建操作任务 NSOperation
    
    // 类型1:NSInvocationOperation
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download1) object:nil];
    NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download2) object:nil];
//    [op1 start];// 操作如果单独start,不加入队列,是在当前线程执行
//    [op2 start];
    
    // 类型2:block任务
    NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"%@:%s start!",[NSThread currentThread],__func__);
        [NSThread sleepForTimeInterval:0.1];
        NSLog(@"%@:%s ended!",[NSThread currentThread],__func__);
    }];
    [op3 addExecutionBlock:^{
        NSLog(@"%@:%s start!",[NSThread currentThread],__func__);
        [NSThread sleepForTimeInterval:0.1];
        NSLog(@"%@:%s ended!",[NSThread currentThread],__func__);
    }];// op3内的block任务始终是并发的。
    
    // 类型3: 自定义任务
    MyOperation *op4 = [[MyOperation alloc] init];
    
    // 3. 添加到队列
    [queue addOperation:op1];// [op1 start];
    [queue addOperation:op2];
    [queue addOperation:op3];
    [queue addOperation:op4];
    
    
}

- (void)download1
{
    NSLog(@"%@:%s start!",[NSThread currentThread],__func__);
    [NSThread sleepForTimeInterval:0.1];
    NSLog(@"%@:%s ended!",[NSThread currentThread],__func__);
}
- (void)download2
{
    NSLog(@"%@:%s start!",[NSThread currentThread],__func__);
    [NSThread sleepForTimeInterval:0.1];
    NSLog(@"%@:%s ended!",[NSThread currentThread],__func__);
}



@end
